<template>
  <div class="dashboard-editor-container">
    <el-row :gutter="40">
      <el-col :sm="24" :xs="24" :md="6" :xl="6" :lg="6" :style="{ marginBottom: '12px' }">
        <div @click="queryAllList">
          <chart-card title="申请总数" :total="totalInfo.applyTotal" style="cursor: pointer" background="rgb(77, 112, 255)">
            <img slot="icon" src="@/assets/all.png" alt="">
          </chart-card>
        </div>
      </el-col>
      <el-col :sm="24" :xs="24" :md="6" :xl="6" :lg="6" :style="{ marginBottom: '12px' }">
        <div @click="queryCompleteList">
          <chart-card title="已完成" :total="totalInfo.finishTotal" style="cursor: pointer" background="rgb(103, 194, 58)">
            <img slot="icon" src="@/assets/complete.png" alt="">
          </chart-card>
        </div>
      </el-col>
      <el-col :sm="24" :xs="24" :md="6" :xl="6" :lg="6" :style="{ marginBottom: '12px' }">
        <div @click="queryProcessList">
          <chart-card title="进行中" :total="totalInfo.runTotal" style="cursor: pointer" background="rgb(230, 162, 60)">
            <img slot="icon" src="@/assets/process.png" alt="">
          </chart-card>
        </div>
      </el-col>
      <el-col :sm="24" :xs="24" :md="6" :xl="6" :lg="6" :style="{ marginBottom: '12px' }">
        <div @click="queryProcessList">
          <chart-card title="年审中" :total="totalInfo.yearTotal" style="cursor: pointer" background="rgb(230, 162, 60)">
            <img slot="icon" src="@/assets/process.png" alt="">
          </chart-card>
        </div>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <el-form ref="listQuery" :model="listQuery" :inline="true">
        <el-form-item label="上报时间">
          <el-date-picker v-model="listQuery.fillTime" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="项目名称" prop="title">
          <el-input v-model="listQuery.name" placeholder="请输入项目名称" clearable size="small" style="width: 180px" @keyup.enter.native="getList" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="listQuery.applyDeptId" clearable placeholder="请选择">
            <el-option v-for="item in deptList" :key="item.id" :label="item.depName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="申报人">
          <el-input v-model="listQuery.applyUser" clearable size="small" style="width: 180px" @keyup.enter.native="getList" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="listQuery.applyManagerName" placeholder="请输入负责人" clearable size="small" style="width: 180px" @keyup.enter.native="getList" />
        </el-form-item>
        <el-form-item label="项目分类">
          <el-select v-model="listQuery.projectClass" clearable placeholder="请选择">
            <el-option v-for="item in projectClassList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="收费编码">
          <el-input v-model="listQuery.chargeCode" placeholder="请输入" clearable size="small" style="width: 180px" @keyup.enter.native="getList" />
        </el-form-item>
        <el-form-item label="审批状态">
          <el-select v-model="listQuery.status" clearable placeholder="请选择">
            <el-option v-for="item in circulationStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="onSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          <el-button v-permisaction="['export:XjsProjectQuery']" type="primary" icon="el-icon-download" size="small" @click="handleExportList">导出全部</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        border
        :data="ticketList"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="#" type="index" width="80" align="center" />
        <el-table-column label="项目名称" prop="name" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="院内项目编号" prop="projectNo" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="项目分类" :show-overflow-tooltip="true" prop="projectClassName" align="center" width="120" />
        <el-table-column label="负责人姓名" :show-overflow-tooltip="true" prop="applyManagerName" align="center" width="120" />
        <el-table-column label="上报人" prop="applyUserName" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="科室" prop="deptName" :show-overflow-tooltip="true" align="center" width="120" />
        <el-table-column label="上报时间" align="center" prop="fillTime" width="180" />
        <el-table-column label="审批状态" prop="statusName" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="500" fixed="right">
          <template slot-scope="scope">
            <el-button v-permisaction="['open:XjsProjectQuery']" size="mini" type="text" icon="el-icon-s-check" @click="handlekzView(scope.row)">开展情况</el-button>
            <el-button v-permisaction="['queryAnnual:XjsProjectQuery']" size="mini" type="text" icon="el-icon-s-check" @click="handleNsView(scope.row)">年审记录</el-button>
            <el-button v-permisaction="['detail:XjsProjectQuery']" size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)">项目详情</el-button>
            <el-button v-permisaction="['history:XjsProjectQuery']" size="mini" type="text" icon="el-icon-time" @click="handleHistoryView(scope.row)">审批历史</el-button>
            <el-button v-permisaction="['exportone:XjsProjectQuery']" size="mini" type="text" icon="el-icon-download" @click="handleExport(scope.row)">导出此行</el-button>
            <el-button v-permisaction="['delete:XjsProjectQuery']" size="mini" type="text" icon="el-icon-delete" class="del-btn" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-dialog width="400px" custom-class="techDialog" title="阶段评审记录" :visible.sync="nsVisible">
        <div class="flex flex-column align-left">
          <el-link
            v-for="(item, index) in currentNs"
            :key="index"
            type="primary"
            :underline="false"
            class="font16 mt10"
          >第{{
            index + 1 }}次阶段评审:
            {{ parseTime(item.complete_time) }}</el-link>
        </div>
      </el-dialog>

      <el-dialog title="转交" :visible.sync="dialogVisible" width="30%">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="60px" class="demo-ruleForm">
          <el-form-item label="节点" prop="node_id">
            <el-select v-model="ruleForm.node_id" placeholder="选择节点" size="small" style="width: 100%">
              <el-option v-for="(item, index) in nodeList" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户" prop="user_id">
            <el-select v-model="ruleForm.user_id" filterable placeholder="选择用户" size="small" style="width: 100%">
              <el-option v-for="(item, index) in users" :key="index" :label="item.nickName" :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="ruleForm.remarks" type="textarea" size="small" />
          </el-form-item>
          <el-form-item style="text-align: right">
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-dialog> -->
      <pagination v-show="pageInfo.total > 0" :total="pageInfo.total" :page.sync="pageInfo.currentPage" :limit.sync="pageInfo.pageSize" @pagination="getList" />
    </el-card>
    <ReviewDialog ref="reviewDialog" @refreshTable="getList" />
    <HistoryDialog ref="historyDialog" source="apply" />
    <RecordDialog v-if="recordVisible" ref="recordRef" :visible.sync="recordVisible" />
  </div>
</template>

<script>
import {
  doDelete,
  selectAllByPage,
  selectAllByTotal,
  unityWorkOrder,
  inversionWorkOrder
} from '@/api/xjs/work-order'
import { getNewDeptList } from '@/api/system/dept'
import RecordDialog from '@/views/xjsxxm/components/annualRecords.vue'
import { listAllUser } from '@/api/system/sysuser'
import HistoryDialog from '@/views/xjsxxm/components/history'
import ReviewDialog from '../components/review'
// 搜索
import ChartCard from './components/ChartCard'
import { mapGetters } from 'vuex'
import { formatJson } from '@/utils'
import { projectClassList } from '@/utils/common'
export default {
  name: 'DashboardAdmin',
  components: {
    ChartCard,
    HistoryDialog,
    ReviewDialog,
    RecordDialog
  },
  computed: {
    ...mapGetters(['circulationStatus'])
  },
  data() {
    return {
      timeValue: '',
      dashboardValue: {
        count: {}
      },
      recallDisabled: false,
      recordVisible: false,
      users: [],
      userMap: {},
      nodeList: [],
      nsVisible: false,
      dialogVisible: false,
      queryParams: {},
      total: 0,
      loading: false,
      ticketList: [],
      currentNs: [],
      projectClassList: projectClassList, // 项目分类列表
      deptList: [], // 科室列表
      listQuery: {
        fillTime: '', // 上报时间
        name: '', // 项目名称
        applyDeptId: '', // 科室id
        applyUser: '', // 申报人
        applyManagerName: '', // 负责人
        projectClass: '', // 项目分类
        chargeCode: '' // 收费编码
      },
      listQueryCopy: null,
      pageInfo: { // 分页信息
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      totalInfo: {
        applyTotal: 0,
        finishTotal: 0,
        runTotal: 0,
        yearTotal: 0
      },
      ruleForm: {
        work_order_id: '',
        node_id: '',
        user_id: '',
        remarks: ''
      },
      rules: {
        node_id: [{ required: true, message: '请选择节点', trigger: 'change' }],
        user_id: [{ required: true, message: '请选择用户', trigger: 'change' }]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  created() {
    this.listQueryCopy = JSON.parse(JSON.stringify(this.listQuery))
    this.getList()
    this.getDeptList()
    this.getInitData()
  },
  methods: {
    // 获取科室
    getDeptList() {
      getNewDeptList({ currentPage: 1, pageSize: 1000 }).then(res => {
        console.log(res)
        // const records = res.records[0]
        this.deptList = res.records
      })
    },
    onSearch() {
      this.pageInfo.currentPage = 1
      this.getList()
    },
    handlekzView(row) {
      this.$alert('暂无开展情况', '提示', {
        confirmButtonText: '确定'
      })
    },
    handleNsView(row) {
      this.recordVisible = true
      this.$nextTick(() => {
        this.$refs.recordRef.open(row.id)
      })
      // this.$alert('暂无年审记录', '提示', {
      //   confirmButtonText: '确定'
      // })
    },
    // 获取全部列表数据
    getAllList() {
      return new Promise((resolve, reject) => {
        const params = {
          ...this.listQuery,
          pageNum: 1,
          pageSize: 99999
        }
        selectAllByPage(params).then(res => {
          res.records.forEach(item => {
            const projectObj = this.projectClassList.find(it => it.value === item.projectClass)
            const statusObj = this.circulationStatus && this.circulationStatus.find(it => it.value === item.status)
            item.projectClassName = projectObj ? projectObj.label : ''
            item.statusName = statusObj ? statusObj.label : ''
          })
          resolve(res.records)
        })
      })
    },
    handleExportList() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(async excel => {
        const tHeader = ['项目名称', '院内项目编号', '项目分类', '负责人姓名', '上报人', '科室', '上报时间', '审批状态']
        const filterVal = ['name', 'projectNo', 'projectClassName', 'applyManagerName', 'applyUserName', 'deptName', 'fillTime', 'statusName']
        const listData = await this.getAllList()
        const data = formatJson(filterVal, listData)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '新技术项目数据',
          autoWidth: true, // Optional
          bookType: 'xlsx' // Optional
        })
        this.downloadLoading = false
      })
    },
    handleExport(row) {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['项目名称', '院内项目编号', '项目分类', '负责人姓名', '上报人', '科室', '上报时间', '审批状态']
        const filterVal = ['name', 'projectNo', 'projectClassName', 'applyManagerName', 'applyUserName', 'deptName', 'fillTime', 'statusName']
        const data = formatJson(filterVal, [row])
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: row.title + '-数据',
          autoWidth: true, // Optional
          bookType: 'xlsx' // Optional
        })
        this.downloadLoading = false
      })
    },
    // 重置
    resetQuery() {
      this.listQuery = JSON.parse(JSON.stringify(this.listQueryCopy))
      this.getList()
    },
    // 获取数据
    getInitData() {
      selectAllByTotal(this.queryList).then(response => {
        if (response) {
          const data = response.records[0]
          this.totalInfo = data
        }
      })
    },
    queryAllList() {},
    queryCompleteList() {},
    queryProcessList() {},
    getList() {
      this.loading = true
      const params = {
        ...this.listQuery,
        ...this.pageInfo
      }
      selectAllByPage(params).then(res => {
        res.records.forEach(item => {
          const projectObj = this.projectClassList.find(it => it.value === item.projectClass)
          const statusObj = this.circulationStatus && this.circulationStatus.find(it => it.value === item.status)
          item.projectClassName = projectObj ? projectObj.label : ''
          item.statusName = statusObj ? statusObj.label : ''
        })
        this.ticketList = res.records
        this.pageInfo.total = res.total
        this.loading = false
      })
    },
    // 表单数据弹窗
    handleView(row) {
      // this.$refs.reviewDialog.open(row.process, row.id)
      // this.$refs.reviewDialog.getNewDeptTreeList()
      this.$refs.reviewDialog.open(row)
    },
    // 查看进度和审批历史弹窗
    handleHistoryView(row) {
      this.$refs.historyDialog.open(row)
    },
    handleDelete(row) {
      this.$confirm(`确认是否删除【${row.name}】该数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          doDelete({ id: row.id }).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
        })
    },
    handleUnity(row) {
      this.$confirm('此操作将会结束该工单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          unityWorkOrder({
            work_oroder_id: row.id
          }).then(response => {
            if (response.code === 200) {
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    handleInversion(row) {
      this.dialogVisible = true
      this.ruleForm.work_order_id = row.id
      this.nodeList = row.state
      if (this.nodeList.length === 1) {
        this.ruleForm.node_id = this.nodeList[0].id
      }
      listAllUser({}).then(response => {
        this.users = response.data
      })
    },
    handleSelectionChange() { },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          inversionWorkOrder(this.ruleForm).then(response => {
            if (response.code === 200) {
              this.getList()
              this.dialogVisible = false
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
    padding: 12px;
    background-color: rgb(240, 242, 245);
    position: relative;

    .github-corner {
        position: absolute;
        top: 0;
        border: 0;
        right: 0;
    }

    .chart-wrapper {
        background: #fff;
        padding: 16px 16px 0;
        margin-bottom: 32px;
    }
}

::v-deep .el-tabs__item {
    padding-left: 16px !important;
    height: 50px;
    line-height: 50px;
}

@media (max-width: 1024px) {
    .chart-wrapper {
        padding: 8px;
    }
}

.leaderboard {
    height: 448px;
    overflow: auto;
}
</style>
